<template>
  <div class="content">
    <div class="content_left">
      1212
    </div>
    <div class="content_right">
      <div class="MsgBox" ref="scroller">
        <div class="msgFlexBox" v-for="(item, index) in msgList" :key="index">
          <div class="isOthers">
            <div
              style="margin: 5px 20px; color: #666"
              v-if="item.userId != userInfo.userId"
            >
              {{ item.name }} {{ item.time }}
            </div>
            <span
              class="msgContentBox isLeft"
              v-if="item.userId != userInfo.userId"
            >
              {{ item.msg }}
            </span>
          </div>
          <div class="isMe">
            <span
              class="msgContentBox isRight"
              v-if="item.userId == userInfo.userId"
            >
              {{ item.msg }}
            </span>
          </div>
        </div>
      </div>
      <div class="isTextarea" v-if="isPc">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="msg"
          @keydown.enter="sendMessage"
        ></el-input>
        <el-button type="primary" class="submitBtn" plain @click="sendMessage"
          ><el-icon style="margin-right: 10px"><Promotion /></el-icon
          >发送</el-button
        >
      </div>
      <div class="isNoPc" v-else>
        <el-input
          type="text"
          placeholder="请输入内容"
          v-model="msg"
          style="flex: 1; padding-right: 5px"
        ></el-input>
        <el-button
          style="width: 80px; height: 30px"
          type="success"
          class="submitBtn"
          @click="sendMessage"
          ><el-icon style="margin-right: 10px"><Promotion /></el-icon
          >发送</el-button
        >
      </div>
    </div>
  </div>
</template>
  <script>
export default {
  data() {
    return {
      msg: "",
      userInfo: {},
      ws: null,
      msgList: [],
      isPc: false,
    };
  },
  created() {
    // 连接WebSocket服务器
    // this.ws = new WebSocket("ws://api.thgcloud.cn:46210");
    this.ws = new WebSocket("ws://localhost:46210");

    // 监听连接打开事件
    this.ws.onopen = () => {
      console.log("WebSocket connected");
      this.loginMsg();
    };

    // 监听消息事件
    this.ws.onmessage = (event) => {
      if (localStorage.getItem("msgList")) {
        this.msgList = JSON.parse(localStorage.getItem("msgList"));
      } else {
        this.msgList = [];
      }
      console.log(event.data, "----------");
      let dataObj = JSON.parse(event.data);
      if (dataObj.type == "up") {
        this.$message.success(`${dataObj.name}上线了`);
      }
      this.msgList.push(JSON.parse(event.data));
      this.msgList = this.msgList.filter((user) => user.type == "msg");
      localStorage.setItem("msgList", JSON.stringify(this.msgList));
      this.msg = "";
      // console.log(this.msgList);
      this.$nextTick(() => {
        this.$refs.scroller.scrollTop = this.$refs.scroller.scrollHeight;
      });
    };

    // 监听连接关闭事件
    this.ws.onclose = () => {
      console.log("WebSocket closed");
    };
  },
  mounted() {
    this.isPc = window.innerWidth > 768;
    let info = sessionStorage.getItem("userInfo");
    this.userInfo = JSON.parse(info);
    if (localStorage.getItem("msgList")) {
      this.msgList = JSON.parse(localStorage.getItem("msgList"));
    } else {
      this.msgList = [];
    }
    console.log(
      this.$refs.scroller.scrollTop,
      this.$refs.scroller.scrollHeight,
      "lll"
    );
    this.$nextTick(() => {
      this.$refs.scroller.scrollTop = this.$refs.scroller.scrollHeight;
    });
    // if (this.isMobileDevice()) {
    //   this.enterFullScreen();
    // }
    console.log(this.userInfo);
    // this.loginMsg()
  },
  methods: {
    formatTimestamp(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 判断是否为移动设备
    isMobileDevice() {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        navigator.userAgent
      );
    },
    // 进入全屏模式
    enterFullScreen() {
      const element = document.documentElement; // 获取文档根元素
      // 请求全屏显示
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.webkitRequestFullscreen) {
        /* Safari */
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) {
        /* IE11 */
        element.msRequestFullscreen();
      }
    },
    // 页面初始化全屏展示
    enterFullScreen() {
      const a = document.documentElement; // 获取页面根元素
      if (a.requestFullscreen) {
        a.requestFullscreen(); // 调用浏览器原生的 Fullscreen API 进入全屏模式
      } else if (a.mozRequestFullScreen) {
        /* Firefox */
        a.mozRequestFullScreen();
      } else if (a.webkitRequestFullscreen) {
        /* Chrome, Safari & Opera */
        a.webkitRequestFullscreen();
      } else if (a.msRequestFullscreen) {
        /* IE/Edge */
        a.msRequestFullscreen();
      }
    },
    sendMessage(event) {
      console.log(11);
      if (!this.msg || this.msg == "") {
        this.$message.error("请输入内容！");
        return false;
      }
      if (event && event.shiftKey) {
        // 如果按下了 Shift 键，则不执行任何操作，允许输入换行
        return;
      }

      // 发送消息给服务器
      let json = {
        name: this.userInfo.userName,
        userId: this.userInfo.userId,
        msg: this.msg,
        type: "msg",
        token: this.userInfo.token,
        time: this.formatTimestamp(new Date()),
      };
      this.ws.send(JSON.stringify(json));
      this.msgList.push({
        name: this.userInfo.userName,
        userId: this.userInfo.userId,
        type: "msg",
        msg: this.msg,
        time: this.formatTimestamp(new Date()),
      });
      this.msg = "";
      this.msgList = this.msgList.filter((user) => user.type == "msg");
      localStorage.setItem("msgList", JSON.stringify(this.msgList));
      this.$nextTick(() => {
        this.$refs.scroller.scrollTop = this.$refs.scroller.scrollHeight;
      });
    },
    loginMsg() {
      // 发送消息给服务器
      let json = {
        name: this.userInfo.userName,
        userId: this.userInfo.userId,
        type: "up",
        token: this.userInfo.token,
      };
      this.ws.send(JSON.stringify(json));
    },
  },
};
</script>
  <style lang="scss" scoped>
@media (max-width: 767px) {
  /* 在这里写入针对小屏幕的样式 */
  .MsgBox {
    height: calc(100% - 45px);
  }
}

/* 当屏幕宽度大于等于 768px 时应用的样式 */
@media (min-width: 768px) {
  /* 在这里写入针对大屏幕的样式 */
  .MsgBox {
    height: calc(100% - 200px);
  }
}
.content {
  background: url("./bj.jpg");
  height: 100%;
  background-size: cover;
  display: flex;
  width: 100%;
  .content_left {
    width: 280px;
    height: 100%;
    background: #fff;
    opacity: 0.7;
    padding: 10px 15px;
  }
  .content_right {
    height: 100%;
    width: 100%;
    flex: 1;
  }
  .MsgBox {
    width: 100%;
    overflow: auto;
    .msgFlexBox {
      width: 100%;
      padding: 10px 0;
      display: flex;
      overflow: hidden;
      .isOthers {
        flex: 1;
      }
      .isMe {
        flex: 1;
      }
    }
  }
  .isTextarea {
    height: 200px;
    width: 100%;
    position: relative;
    :deep(.el-textarea) {
      height: 100%;
      opacity: 0.7;
    }
    :deep(.el-textarea__inner) {
      height: 100%;
    }
    .submitBtn {
      position: absolute;
      bottom: 10px;
      right: 10px;
      padding: 10px 20px;
      font-weight: bold;
    }
  }
  .isNoPc {
    display: flex;
    background: #f3f3f3;
    padding: 7px 5px;
  }
}
.msgContentBox {
  padding: 13px 28px;
  background: #fff;
  display: inline-block;
  border-radius: 5px;
  box-shadow: 0 2px 4px #0000001a;
}
.isLeft {
  float: left;
  margin-left: 20px;
}
.isRight {
  float: right;
  margin-right: 20px;
  background: rgb(47, 255, 92);
}
/* 自定义滚动条样式 */
/* 整体滚动条轨道 */
::-webkit-scrollbar {
  width: 0;
}
::-webkit-scrollbar-track {
  // -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  // opacity: 0.3;
}
/* 滑块 */
::-webkit-scrollbar-thumb {
  background: #c6c6c6;
  border-radius: 2px; /* 添加圆角 */
}
/* 滑块悬停时 */
::-webkit-scrollbar-thumb:hover {
  background: #c9c9c9;
}
/* 可选 - 隐藏滚动条的轨道 */
// ::-webkit-scrollbar-track {
//   -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
// }
</style>